var util = require('../../utils/util.js');
var base64 = require('../../utils/base64.js');
var api = require('../../config/api.js');
const aliSdk = require("../../utils/ali_iot_util/aliIot-sdk.js")



//获取应用实例
const app = getApp()
Page({
    data: {
      myintervalid:0,
      userlogined_flag: 0,
      userInfo: {},
      showLoginDialog: false,
      now_time:parseInt(new Date().getTime() / 1000),

      scanresult:'',      //扫面二维码结果
      device_name:[],
      device_uuid:[],
      gprs_number:[],
      scandevicelist: [],  //扫描设备的查询信息
      // text:"这是一个页面"
      topicList: [],
      deviceupdatalist:[],
      page: 1,
      size: 10,
      count: 0,
      scrollTop: 0,
      showPage: false,

      goodsCount: 0,
      newGoods: [],
      hotGoods: [],
      topics: [],
      brands: [],
      floorGoods: [],
      banner: [],
      channel: []

    },
  onShareAppMessage: function () {
    return {
      title: 'AUTOHeat',
      desc: '通然物联平台',
      path: 'pages/topic/topic'
    }
  },

    onLoad: function (options) {



    },
    onReady: function () {
        // 页面渲染完成
    },
    onShow: function () {
        // 页面显示
        this.onUserInfoClick();
        var that = this;

        var data1 = {
            adc: 111,
            iostate: "1201",
            power: "abcd"
          };
        // 读取设备属性状态
        // const config1 = {
        //   Action: "QueryDevicePropertyStatus",
        //   ProductKey: api.productKey,
        //   DeviceName: api.deviceName
        // };
        // RRPC 向指定设备发送请求消息，并同步返回响应
        const config1 = {
          Action: "RRpc",
          ProductKey: api.productKey,
          DeviceName: api.deviceName,
          timeout: 6666,
          requestBase64Byte: base64.encode(JSON.stringify(data1)),
        };
        aliSdk.request(config1, {
          method: "POST"
        },
        (res) => {
          console.log("success")
          console.log(res) //查看返回response数据
          if (res.data.Code) {
            console.log(res.data.ErrorMessage)
            wx.showToast({
              title: '设备连接失败',
              icon: 'none',
              duration: 1000,
              complete: () => {}
            })
            // that.setPropertyData(null)
            console.log("1111nihao ")
          } else {
            // console.log("2222nihao ",res);
            console.log("2222nihao ",JSON.parse(base64.decode(res.data.PayloadBase64Byte)));
            // that.setPropertyData(res.data.Data.List.PropertyStatusInfo)
          }
        },
        (res) => {
          console.log("fail")
          wx.showToast({
            title: '网络连接失败',
            icon: 'none',
            duration: 1000,
            complete: () => {}
          })
          // this.setPropertyData(null)
        },
        (res) => {
          console.log("complete")
          
        })








        //批量 添加龙onenet数据到 云数据库
        //定时onenet添加设备信息到 云数据库
      //   var fori = 0;
      //   var device_name = 0;
      //   var onenet_deviceid=635491177;

      //   //周期为：3秒 的周期定时器 
      // that.data.myintervalid = setInterval(function () {
      //   if(fori <= 99){
      //     wx.cloud.callFunction({
      //       name: 'addonenetdata',
      //       data: { onenet_deviceid: onenet_deviceid+fori,
      //         device_name: fori+101,
      //         onenet_pid: 311038,
      //         ondevice_key: 'deng dai tianjia',
      //       }
      //     }).then(res => {
      //       console.log("that.data.device_name res = ", res);
      //       if (res.errMsg === "cloud.callFunction:ok"){
      //         fori = fori +1;
              
      //       }else{

      //       }
      //     })

      //   }

      //   }, 3000)

        if (that.data.userlogined_flag === 1) {

          that.getTopic();

        }
    },
    onHide: function () {
        // 页面隐藏
        //关闭  周期为：2秒 的周期定时器
      clearInterval(this.data.myintervalid);
    },
    onUnload: function () {
        // 页面关闭
        //关闭  周期为：2秒 的周期定时器
      clearInterval(this.data.myintervalid);
    },
    switch1Change: function (e) {
    },
    //下拉刷新
    onPullDownRefresh: function () {
      this.onShow();
    },
    //控制设备  跳转到设备控制页面 Form表单提交数据
  ctrldevices: function (e) {
    //跳转到设备控制页面 Form表单提交数据
    console.log('控制设备开始22222',e);
    const devicesupdata3 = this.data.deviceupdatalist;
    console.log('控制设备开始1111',this.data.deviceupdatalist);
    for (var devicedataItem of devicesupdata3) {
      if (devicedataItem.device_name == e.currentTarget.id) {
        wx.navigateTo({
          //通过 URL  id 传值 传递的值为 设备logicID  和 设备 页面显示的设备 序号
          url: "../ctrldevices/ctrldevices?id="+devicedataItem.device_name+"&onenet_deviceid="+devicedataItem.onenet_deviceid

        });
      }
    }
  },


  renew: function (e) {
    wx.showModal({
      title: '提示',
      content: '您确认要续费吗？',
      success(res) {
        if (res.confirm) {
          console.log("poem_id=" + e.currentTarget.id);
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //扫面二维码 方法
  scanCode() {
    const that = this
    wx.scanCode({
      success(res) {
        console.log('resstr11 =', res);
        that.setData({
          scanresult: res.result
        })
        if ((that.data.scanresult[0] === '{') && (that.data.scanresult[1] === '"') && (that.data.scanresult[2] === 'd') && (that.data.scanresult[3] === 'e') && (that.data.scanresult[4] === 'v'))
        {
          const str11 = JSON.parse(res.result);
          console.log('str11 =', str11.device_name);

          that.setData({
            device_name: str11.device_name,
            gprs_number: str11.desc,
            userInfo: wx.getStorageSync('userInfo')
          })
          // that.showLoginDialog();

          wx.cloud.callFunction({
            name: 'getuserdvc',
            data: {type:"1",
              skip:0,
              limit:20,
              device_name: str11.device_name

            }
          }).then(res => {
            console.log("that.data.device_name res555 = ", res);
            console.log("that.data.device_name res666 = ", that.data.device_name);
            if (res.errMsg === "cloud.callFunction:ok"){
              if (res.result.data.length === 0){
                that.showLoginDialog();
                that.setData({
                  scandevicelist: res.data
                })
                console.log("that.data.device_name res = ", that.data.scandevicelist);
               
              }else {
                if (res.result.data[0].device_name === that.data.device_name){
                  // 页面渲染完成
                  wx.showToast({
                    title: '该设备已存在！',
                    icon: 'success',
                    duration: 2000
                  });
                }
                
              }

            }
          })


          wx.hideToast();


        }else{
          wx.showToast({
            title: '条码不正确！添加设备失败！',
            // title: '添加设备失败！',
            icon: 'none',
            duration: 2000
          }); 
        }
        // wx.hideToast();
      },
      fail() { }
    })
  },
  //扫面二维码 后确认添加设备，确认按钮回调方法
  scanaddCode() {
    const that = this

    wx.cloud.callFunction({
      name: 'scandevice',
      data: { device_name: that.data.device_name, 
              gprs_number: that.data.gprs_number[0],
      }
    }).then(res => {
      console.log("that.data.device_name res777 = ", res);
      if (res.errMsg === "cloud.callFunction:ok"){
        // 页面渲染完成
        that.getTopic();
        wx.showToast({
          title: '添加设备成功！',
          icon: 'success',
          duration: 2000
        });
        that.onCloseLoginDialog();
        
      }else{
        // 页面渲染完成
        wx.showToast({
          title: '该设备已存在！',
          icon: 'success',
          duration: 2000
        });
      }
    })

    wx.hideToast();
  },
    nextPage: function (event) {
        var that = this;
        if (this.data.page+1 > that.data.count / that.data.size) {
            return true;
        }
        that.setData({
            "page": parseInt(that.data.page) + 1
        });
        this.getTopic(); 
    },
    getTopic: function(){
       
        let that = this;
         that.setData({
            scrollTop: 0,
            showPage: false,
            topicList: []
        });
      //提示微信登录
      // this.onUserInfoClick();
        // 页面渲染完成
        wx.showToast({
            title: '加载中...',
            icon: 'loading',
            duration: 2000
        });

        wx.cloud.callFunction({
          name: 'getuserdvc',
          data: {type:"2",
            skip:0,
            limit:20,

          }
        }).then(res => {
          console.log("that.data.device_name res666 = ", res);
          that.setData({
            scrollTop: 0,
            topicList: res.result.data,
            deviceupdatalist: res.result.data,
            showPage: true,
            count: res.result.data.length
          });

        })


        
    },

    onUserInfoClick: function () {
      if (wx.getStorageSync('userInfo')) {
        // wx.clearStorageSync('userInfo');
        // wx.clearStorageSync('token');
        this.setData({
          userlogined_flag: 1
        });
        // this.getTopic();
      } else {
        // this.showLoginDialog();
      }
    },
    showLoginDialog() {
      this.setData({
        showLoginDialog: true
      })
    },
    onCloseLoginDialog() {
      this.setData({
        showLoginDialog: false
      })
    },

    onWechatLogin(e) {
      console.log( "微信登录信息 = ", e);
      if (e.detail.errMsg !== 'getUserInfo:ok') {
        if (e.detail.errMsg === 'getUserInfo:fail auth deny') {
          wx.showToast({
            icon: 'none',
            title: '微信登录失败',
          })
          return false
        }
        // wx.showToast({
        //   title: '微信登录失败',
        // })
        // return false
      }
      setTimeout(()=>{
        wx.cloud.callFunction({
          name: 'login',
          data: {
          }
        }).then(res => {
          if(res.result.data.length>0){
            console.log('res: ', res)
            let userInfo= res.result.data[0]
            // 设置用户信息
            this.setData({
              userInfo: res.data.userInfo,
              showLoginDialog: false,
              userlogined_flag: 1
            });
            app.globalData.userInfo = userInfo;

            wx.setStorageSync('userInfo', JSON.stringify(userInfo));
            this.onLoad();
          }else{
            wx.showToast({
              icon: 'none',
              title: '微信登录失败',
            })
            return false;
            
          }
        }) 
      },1000)
      
      
    },
    //结清尾款
  collectingamount: function () {
    let that = this;
    wx.navigateTo({
      // url:  "/pages/goods/goods?id={{iitem.id}}",
      url: "/pages/goods/checkout/checkout?goodsid=1181016&productId=255&device_name="+that.data.device_name,

    })
  },

    prevPage: function (event) {
        if (this.data.page <= 1) {
            return false;
        }

        var that = this;
        that.setData({
            "page": parseInt(that.data.page) - 1
        });
        this.getTopic();
    }
})